#include "timer.h"
#include "system.h"
#include "irq.h"

unsigned int timer_ticks = 0;
struct timed_func func;

void timer_phase(int hz){
	unsigned short divisor = 1193180 / hz;       /* Calculate our divisor */
	outportb(PIT_COMMAND, 0x34);             /* Set our command byte 0x36 */
	outportb(PIT_CHAN0, divisor & 0xFF);   /* Set low byte of divisor */
	outportb(PIT_CHAN0, divisor >> 8);     /* Set high byte of divisor */
}

void timer_handler(struct regs *r){
	timer_ticks++;

	if (timer_ticks - func.last_call > func.interval){
		func.last_call = timer_ticks;
		func.func();
	}
}

void timer_install(){
	timer_phase(TIMER_FREQ);
	irq_install_handler(0, timer_handler);
}

int uptime(){
	return timer_ticks / TIMER_FREQ;
}

void reg_timed_func(int interval, void (*mfunc) (void)){
	func.last_call = 0;
	func.interval = interval;
	func.func = mfunc;
}
